package top.vanchor.flexible.controller.publics;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;
import io.swagger.annotations.Api;
import lombok.extern.log4j.Log4j2;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import top.vanchor.flexible.common.Res;
import top.vanchor.flexible.config.consts.OssConst;
import top.vanchor.flexible.entity.ResourcePath;
import top.vanchor.flexible.service.IResourcePathService;
import top.vanchor.flexible.service.impl.ResourcePathServiceImpl;
import top.vanchor.flexible.utils.FileUtil;
import top.vanchor.flexible.utils.ImageAddress;
import top.vanchor.flexible.utils.JWTUtils;
import top.vanchor.flexible.utils.MinioUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Ding
 * @create 2022/1/27 12:30
 */
@Log4j2
@Api("文件上传")
@Controller
@CrossOrigin
@RestController
@RequestMapping("/public")
public class PublicController {
    @Resource
    private IResourcePathService service;

    @Autowired
    private ResourcePathServiceImpl resourcePathServiceImpl;

    @Autowired
    private MinioUtils minioUtil;

    /**
     * 文件上传
     *
     * @param file     文件
     * @param request  请求
     * @param response 响应
     * @return 文件路径
     * @throws IOException 异常
     */
    @PostMapping("/upload")
    @ResponseBody
    public JSONObject uploadFile(@RequestParam MultipartFile file,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws IOException, UnsupportedAudioFileException {
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        //创建随机文件名
        String filename = UUID.randomUUID().toString().replaceAll("-", "");
        //文件后缀
        String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //新文件名
        String newFileName = filename + ext;
        //获取上传的输入流
        InputStream inputStream = file.getInputStream();
        //设置访问地址是默认是预览图片
        ObjectMetadata meta = new ObjectMetadata();
        //设置文件的类型
        long videoLength = 0;
        if (".mp4".equals(ext)) {
            //视频格式
            meta.setContentType("video/mp4");
            videoLength = FileUtil.getVideoDuration(file, filename, ext);
        } else {
            //图片格式
            if (!".zip".equals(ext) && !".xlsx".equals(ext)) {
                meta.setContentType("image/jpg");
            }
        }
        // 创建OSSClient实例
        String upload = minioUtil.upload(newFileName, file);
        JSONObject jsonObject = new JSONObject();;
        ResourcePath ruralResource = new ResourcePath();
        ruralResource.setUrl(newFileName);
        if (service.toAddItem(ruralResource) > 0) {
            jsonObject.put("stat", 200);
            jsonObject.put("url", ImageAddress.getAllPath(upload));
            jsonObject.put("resourceId", ruralResource.getRId());
            if (videoLength > 0) {
                jsonObject.put("videoLength", videoLength);
            }
            log.info("{}{}（ID为{}）进行了一次文件上传，文件大小{}b", JWTUtils.getAuthorTypeName(), JWTUtils.getAuthorName(), JWTUtils.getAuthorId(), file == null ? -1 : file.getSize());
        } else {
            jsonObject.put("stat", 500);
            log.error("{}{}（ID为{}）进行了一次失败的文件上传，若OSS传输成功，则原因可能是链接入库失败", JWTUtils.getAuthorTypeName(), JWTUtils.getAuthorName(), JWTUtils.getAuthorId());
        }
        return jsonObject;
    }


    @GetMapping("/getVertifyCode")
    public Res<JSONObject> staticPage() {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 90, 4, 100);
        // 验证码值
        String code = lineCaptcha.getCode();
        return Res.success(new JSONObject() {{
            put("code", code);
            put("base64", lineCaptcha.getImageBase64Data());
        }});
    }

}
